//
//  LZTEmoticonKeyboardView.swift
//  LZTWeibo
//
//  Created by Yin jianxun on 16/8/18.
//  Copyright © 2016年 YinJianxun. All rights reserved.
//

import UIKit

class LZTEmoticonKeyboardView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置视图
    func setupUI() {
        
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        //添加控件
        addSubview(emoticonBottomView)
        addSubview(emoticonPageView)
        addSubview(pageControl)
        //添加约束
        emoticonBottomView.snp_makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(self)
            make.height.equalTo(37)
        }
        emoticonPageView.snp_makeConstraints { (make) in
            make.leading.top.trailing.equalTo(self)
            make.bottom.equalTo(emoticonBottomView.snp_top)
        }
        pageControl.snp_makeConstraints { (make) in
            make.bottom.equalTo(emoticonPageView).offset(5)
            make.centerX.equalTo(emoticonPageView)
        }
        
        //底部按钮的闭包回调
        emoticonBottomView.closure = {(type: LZTEmoticonBottomViewType) -> () in
            
            //对应按钮的indexPath
            let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
            
            //设定 键盘下方按钮点击时 表情collectionView的联动
            //atScrollPosition:该滚动是指cell滚动到父控件的哪一侧
            self.emoticonPageView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            
            //设置pageControl 默认展示:第一组的第一页
            self.setupPageControl(indexPath)
            
        }
        
        //设置pageControl 默认展示:第一组的第一页
        setupPageControl(NSIndexPath(forItem: 0, inSection: 0))
        
    }
    
    //懒加载 底部试图
    private lazy var emoticonBottomView: LZTEmoticonBottomView = LZTEmoticonBottomView(frame: CGRectZero)
    
    //懒加载 底部自定义表情键盘
    private lazy var emoticonPageView: LZTEmoticonPageView = {
        
        let view = LZTEmoticonPageView()
        //pageView的颜色设定
        view.backgroundColor = self.backgroundColor
        //分页效果
        view.pagingEnabled = true
        //弹簧效果
        view.bounces = false
        //取消滚动条
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        
        //设置collectionView的滚动代理
        view.delegate = self
        
        return view
    }()
    
    //懒加载 pageControl加在keyboard上面 ：1.能获得底部试图的按钮的点击 2.可以获得pageView的滑动（对应于collectionView的cell）
    private lazy var pageControl: UIPageControl = {
       
        let pageC = UIPageControl()
        
        //默认颜色
//        pageC.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        //由于默认颜色（只读-计算性属性） 设置图片时，会有图片显示问题（会有锯齿感觉），因此，需要对该属性进行KVC赋值
        pageC.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "pageImage")
        
        //选中颜色
//        pageC.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        //处理和 默认颜色一样
        pageC.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "currentPageImage")
        
        //取消用户交互
        pageC.userInteractionEnabled = false
        
        return pageC
    }()

}

//
extension LZTEmoticonKeyboardView: UICollectionViewDelegate {
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //获取相对于表情pageView的centerX
        let centerX = SCREENW * 0.5 + scrollView.contentOffset.x
        
        //获取屏幕显示的cell 排序后的cell
        let cells = self.emoticonPageView.visibleCells().sort { (cell1, cell2) -> Bool in
            return cell1.frame.origin.x < cell2.frame.origin.x
        }
        
        if cells.count == 2 {
            
            let firstCell = cells.first!
            let lastCell = cells.last!
            
            let indexPath: NSIndexPath
            
            //判断 相对中心点 是否在firstCell 或者lastCell中
            //x: centerX - 相对中心点 , y: 0 - 键盘的高度216以内
            if firstCell.frame.contains(CGPoint(x: centerX, y: 0)) {
                
                //水平滑动方向来说：左侧cell包含相对中心 显示左侧按钮
                //确认cell对应的按钮
                indexPath = emoticonPageView.indexPathForCell(firstCell)!
                
            }else {
                
                //水平滑动方向来说：右侧cell包含相对中心 显示右侧按钮
                //确认cell对应的按钮
                indexPath = emoticonPageView.indexPathForCell(lastCell)!
            }
            
            //设置选中的按钮
            emoticonBottomView.setupCurrentButton(indexPath.section)
            
            //设置pageControl 默认展示:第一组的第一页
            setupPageControl(indexPath)
        }
    }
    
    func setupPageControl(indexPath: NSIndexPath) {
        
        //设置pageControl 默认展示:第一组的第一页
        //总页数
        pageControl.numberOfPages = LZTEmoticonTools.sharedTools.allEmoticons[indexPath.section].count
        //默认页数
        pageControl.currentPage = indexPath.item
        
    }
}



